<template>
  <div class="main">
    <div class="loginClass">
      <img src="@/assets/yun-mes.png" alt="" />
    </div>
    <div class="hello">欢迎登录</div>
    <van-form @submit="handleSubmit" @failed="formFailed">
      <div class="loglabel">手机号</div>
      <van-field
        v-model="params.username"
        name="username"
        placeholder="请输入您的手机号"
        :rules="validatorRules.username.rules"
      />
      <div class="loglabel password-top">密码</div>
      <van-field
        v-model="params.password"
        type="password"
        name="password"
        placeholder="请输入密码"
        :rules="validatorRules.password.rules"
      />
      <!-- <van-checkbox v-model="params.rememberMe">自动登录</van-checkbox> -->
      <div class="submit-top">
        <van-button round block type="info" native-type="submit"
          >登录</van-button
        >
      </div>
    </van-form>
    <van-popup v-model="dialogShow" position="bottom">
      <van-picker
        title="请选择租户"
        show-toolbar
        :columns="columns"
        @confirm="onConfirm"
        @cancel="onCancel"
        value-key="tenantName"
      />
    </van-popup>
  </div>
</template>
<script>
import { mapActions } from "vuex";
import { timeFix } from "@/utils/util";
import Vue from "vue";
import {
  ACCESS_TOKEN,
  USER_NAME,
  USER_INFO,
  INTERFACE_PREFIX,
  PLATFORM_BROWSER,
} from "@/store/mutation-types";
import { Tip } from "@/utils";
import { getAction, postAction } from "@/api/manage";
import axios from "axios";
import { apiBaseUrl } from "@/utils/request";
export default {
  data() {
    return {
      columns: [],
      dialogShow: false,
      // loginType: 0 email, 1 username, 2 telephone
      loginType: 0,
      form: this.$form.createForm(this),
      validatorRules: {
        username: {
          rules: [
            { required: true, message: "请输入您的手机号!" },
            { validator: this.handleUsernameOrEmail },
          ],
        },
        password: {
          rules: [
            { required: true, message: "请输入登录密码!" },
            { validator: this.checkPassword, message: "登录密码格式不正确" },
          ],
        },
      },
      params: {
        username: "",
        password: "",
      },
      userId: "",
      loginParams: {},
    };
  },
  created() {
    Vue.ls.remove(ACCESS_TOKEN);
    this.getRouterData();
  },
  methods: {
    ...mapActions(["Login", "Logout", "PhoneLogin"]),
    // handler
    handleUsernameOrEmail(value) {
      console.log(value, "handleUsernameOrEmail");
      const regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;
      if (regex.test(value)) {
        this.loginType = 0;
      } else {
        this.loginType = 1;
      }
      return true;
    },
    checkPassword(value) {
      const regex = /^[\d\w!@#$%^&*()_+=[\]{}|\\,.? -]{6,12}$/;
      return regex.test(value);
    },
    alertWarning(text) {
      this.$toast(text);
    },
    formFailed(params) {
      let values = params.values;
      if (values.password && values.username == "") {
        this.alertWarning("手机号未输入");
      } else if (values.username && values.password == "") {
        this.alertWarning("密码未输入");
      } else if (values.username == "" && values.password == "") {
        this.alertWarning("手机号密码未输入");
      }
    },
    // // 使用账户密码登录
    handleSubmit(values) {
      let loginParams = {};
      loginParams.username = values.username;
      loginParams.password = values.password;
      loginParams.remember_me = values.rememberMe;
      postAction("/sys/getTenantInfoByPhone", {
        phone: loginParams.username,
      }).then((res) => {
        if (res.result && res.result.length > 0) {
          if (res.result.length === 1) {
            this.userId = res.result[0].user.id;
            this.phoneLogin();
          } else {
            this.columns = res.result.map((item) => {
              let obj = {
                tenantName: item.tenantInfo.tenantName,
                id: item.user.id,
              };
              return obj;
            });
            this.dialogShow = true;
          }
        } else {
          this.requestFailed(res);
        }
      });
    },
    phoneLogin() {
      let loginParams = {
        userId: this.userId,
        username: this.params.username,
        password: this.params.password,
        isTenant: "1",
      };
      postAction("/sys/phoneLogin", loginParams)
        .then((res) => {
          if (res.code == 200) {
            this.loginSuccess(res.result);
          } else {
            this.requestFailed(res);
          }
        })
        .catch((err) => {
          this.requestFailed(err);
        });
    },
    queryTenant(rentList, loginParams) {
      axios({
        method: "get",
        headers: {
          "Content-Type": "application/json;charset=UTF-8",
          "X-Access-Token": rentList.token,
        },
        url: apiBaseUrl + "/jksaas-mgt/mgt/sys/queryMgtTenantInfo",
      })
        .then((res) => {
          if (res.data.code == 200) {
            let data = res.data.result;
            if (!data || data.length === 0) {
              this.loginSuccess(rentList);
            } else if (data.length === 1) {
              let obj = {
                tenantId: data[0].id,
                ...loginParams,
              };
              this.loginAfter(obj);
            } else {
              this.columns = data;
              this.dialogShow = true;
            }
          } else {
            this.requestFailed(res);
          }
        })
        .catch((err) => {
          this.$emit("fail", err);
        });
    },
    loginSuccess(result) {
      this.savaStore(result);
      // this.$router.push({ path: "/" }).catch((err) => {});
      // Tip.success(`${timeFix()}，欢迎回来`);
    },
    loginAfter(loginParams) {
      axios({
        method: "post",
        headers: {
          "Content-Type": "application/json;charset=UTF-8",
        },
        url: apiBaseUrl + "/jksaas-mgt/mgt/sys/login",
        data: loginParams,
      })
        .then((res) => {
          if (res.data.code == 200) {
            this.loginSuccess(res.data.result);
          } else {
            this.requestFailed(res.data);
          }
        })
        .catch((err) => {
          this.requestFailed(err);
        });
    },
    requestFailed(err) {
      Tip.error(err.message);
    },
    savaStore(result) {
      Vue.ls.set(PLATFORM_BROWSER, "BROWSER");
      const userInfo = result.userInfo;
      localStorage.setItem("companyName", userInfo.companyName);
      Vue.ls.set(ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000);
      Vue.ls.set(USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000);
      Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000);
      this.$store.commit("SET_TOKEN", result.token);
      this.$store.commit("SET_INFO", userInfo);
      this.$store.commit("SET_NAME", {
        username: userInfo.username,
        realname: userInfo.realname,
      });
      getAction(`/newSys/permission/getRoute`).then((res) => {
        Vue.ls.set(INTERFACE_PREFIX, res.result, 7 * 24 * 60 * 60 * 1000);
        this.$store.commit("SET_INTERFACE_PREFIX", res.result);
        this.$store.commit("SET_AVATAR", userInfo.avatar);
        setTimeout(() => {
          this.$router.push({ path: "/" }).catch((err) => {});
          Tip.success(`${timeFix()}，欢迎回来`);
        }, 20);
      });
    },
    getRouterData() {
      this.$nextTick(() => {
        if (this.$route.params.username) {
          this.form.setFieldsValue({
            username: this.$route.params.username,
          });
        }
      });
    },
    onConfirm(value) {
      this.userId = value.id;
      this.phoneLogin();
      this.onCancel();
    },
    onCancel() {
      this.dialogShow = false;
    },
  },
};
</script>

<style lang="less" scoped>
.main {
  background: #f3fbff url(~@/assets/background.png) no-repeat;
  background-size: 100%;
  height: 100%;
  padding: 0 80px;
  font-family: PingFang SC;

  .password-top{
    margin-top: 40px;
  }
  .submit-top{
    margin-top: 100px;
  }
  .hello {
    font-size: 36px;
    font-weight: bold;
    color: #101328;
    text-align: center;
    margin-bottom: 80px;
  }
  .loglabel {
    font-size: 30px;
    font-weight: 500;
    color: #101328;
    margin-bottom: 20px;
  }
  /deep/.van-field__body {
    font-size: 24px;
    font-weight: 400;
    color: #101328;
  }
}
.loginClass {
  font-size: 24px;
  color: #646566;
  box-sizing: border-box;
  padding: 160px 80px 80px;
  // border-bottom: 0.01rem solid #f0f0f0;
  display: flex;
  justify-content: center;
  img {
    width: 100%;
  }
}
</style>
<style>
.valid-error .ant-select-selection__placeholder {
  color: #f5222d;
}
</style>
